package org.xmx0632.connector.handlers;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 超时检测处理器
 *
 */
@Component
@Sharable
public class TimeoutServerHandler extends ChannelInboundHandlerAdapter {
	private static final Logger LOG = LoggerFactory.getLogger(TimeoutServerHandler.class);

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

		if (evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent) evt;
			if (event.state() == IdleState.READER_IDLE) {
				// 一分钟内没有收到网关(心跳)消息,则认为网关掉线
				// TODO 释放资源,断开连接
				LOG.info("{} read timeout,close client connection now.", ctx.channel().remoteAddress());
				LOG.info(ctx.channel().remoteAddress() + " timeout type:" + event.state());
				ctx.channel().close();
			} else {
				LOG.info(ctx.channel().remoteAddress() + " ignore timeout type:" + event.state());
				super.userEventTriggered(ctx, evt);
			}
			return;
		}

		super.userEventTriggered(ctx, evt);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		LOG.info("msg:{}", msg);
		super.channelRead(ctx, msg);
	}

}
